﻿#region license
// CopyRight (c) 2009-2010 HangJing Teconology. All Rights Reserved.
// Function :礼品信息列表
// Created by tuhui at 2010-6-24 16:28:03.
// E-Mail: tuhui@ihangjing.com
#endregion
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.WebCommon;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.Common;
using System.Collections.Generic;
using org.in2bits.MyXls;

/// <summary>
/// 配送员薪资结算
/// </summary>
public partial class qy_55tuan_Admin_Deliversarly : System.Web.UI.Page
{
    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }

    /// <summary>
    /// 订单查询条件
    /// </summary>
    private string otherwhere
    {
        get
        {
            object o = ViewState["otherwhere"];
            return (o == null) ? "1=1" : o.ToString();
        }
        set
        {
            ViewState["otherwhere"] = value;
        }
    }


    /// <summary>
    /// 当月订单查询条件
    /// </summary>
    private string CurrentMounthwhere
    {
        get
        {
            object o = ViewState["CurrentMounthwhere"];
            return (o == null) ? "OrderStatus=3" : o.ToString();
        }
        set
        {
            ViewState["CurrentMounthwhere"] = value;
        }
    }

    Deliver dal = new Deliver();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlWhere = " 1=1 and delflag = 0 ";
            SqlWhere = new RightsTool().getDeliverWhere(SqlWhere);
            otherwhere = " 1=1 ";

            CurrentMounthwhere = "OrderStatus=3";

            WebUtility.SetDDLCity(ddlcity);
            WebUtility.BindList("id", "classname", SectionProxyData.GetEdelivergroupList(), ddlGpsIMEI);


        }
    }

    private void BindData()
    {
        int RecordCount = 0;

        if ((this.tbStartTime.Text != "" && Convert.ToDateTime(tbStartTime.Text) >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-1")))
            ||
            (this.tbStartmounth.Text != "" && Convert.ToDateTime(tbStartmounth.Text) >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-1")))

            ) //开始时间是本月，根据订单记录实时查询
        {
            IList<DeliverInfo> delivers = dal.CurrentMounthSalarySum(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, CurrentMounthwhere, "ordercount");
            if (delivers.Count > 0)
            {
                RecordCount = delivers[0].recordtcount;
            }
            this.AspNetPager1.RecordCount = RecordCount;

            string sql = CurrentMounthwhere;
            sql += " and EXISTS(SELECT dataid FROM dbo.Deliver WHERE dataid = Custorder.deliverid AND " + SqlWhere + " )";

            //Response.Write(sql);


            DeliverInfo sum = dal.GetCurrentMounthSum(sql);
            DeliverInfo postsum = dal.GetPostSum(SqlWhere);
            sum.UserName = postsum.UserName;
            sum.Password = postsum.Password;
            sum.salary = sum.reveint3 + postsum.reveint2;
            sum.deliverprofit = sum.shopdiscountmoney - sum.salary;

            IList<DeliverInfo> sums = new List<DeliverInfo>();
            sums.Add(sum);

            WebUtility.BindRepeater(rptsum1, sums);
            this.rtpGifts.DataSource = delivers;
            this.rtpGifts.DataBind();
        }
        else
        {
            IList<DeliverInfo> delivers = dal.GetListWithOrderStatistics(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, otherwhere, "ordercount");
            if (delivers.Count > 0)
            {
                RecordCount = delivers[0].recordtcount;
            }
            this.AspNetPager1.RecordCount = RecordCount;

            string sql = otherwhere;
            sql += " and EXISTS(SELECT dataid FROM dbo.Deliver WHERE dataid = DeliverSalaryLog.deliverid AND " + SqlWhere + " )";

            DeliverInfo sum = new DeliverSalaryLog().GetSum(sql);

            IList<DeliverInfo> sums = new List<DeliverInfo>();
            sums.Add(sum);

            WebUtility.BindRepeater(rptsum1, sums);
            this.rtpGifts.DataSource = delivers;
            this.rtpGifts.DataBind();
        }


        AlertScript.RegScript(this.Page, "init();");
    }

    protected void btSearch_Click(object sender, EventArgs e)
    {
        SqlWhere = " 1=1  ";
        SqlWhere = new RightsTool().getDeliverWhere(SqlWhere);
        otherwhere = " 1=1 ";

        CurrentMounthwhere = "OrderStatus=3 and Custorder.delflag = 0 ";

        if (tbKeyword.Text != "")
        {
            SqlWhere += " and  Name like '%" + WebUtility.InputText(tbKeyword.Text) + "%'";
        }


        if (cbremovedel.Checked == true)
        {
            SqlWhere += " and delflag = 0";
        }



        if (ddlcity.SelectedValue != "0")
        {
            SqlWhere += " and Inve1 = " + ddlcity.SelectedValue + "";
        }

        if (ddlGpsIMEI.SelectedValue != "-1")
        {
            SqlWhere += " and GpsIMEI = " + ddlGpsIMEI.SelectedValue + "";
        }

        if (ddreveint1.SelectedValue != "-1")
        {
            SqlWhere += " and reveint1 = " + ddreveint1.SelectedValue + "";
        }
        if (ddlpost.SelectedValue != "-1")
        {
            SqlWhere += " and post = '" + ddlpost.SelectedValue + "'";
        }

        if (ddlgrade.SelectedValue != "-1")
        {
            SqlWhere += " and grade = " + ddlgrade.SelectedValue + "";
        }

        if (ddlcarower.SelectedValue != "-1")
        {
            SqlWhere += " and carower = " + ddlcarower.SelectedValue + "";
        }
        if (tbcartype.SelectedValue != "-1")
        {
            SqlWhere += " and cartype = '" + tbcartype.SelectedValue + "'";
        }



        if (this.tbStartTime.Text != "")
        {
            otherwhere += " and  [starttime] >= '" + WebUtility.InputText(this.tbStartTime.Text) + "' ";
            CurrentMounthwhere += " and  [OrderDateTime] >= '" + WebUtility.InputText(this.tbStartTime.Text) + "' ";
            
        }
        if (this.tbEndTime.Text != "")
        {
            otherwhere += " and starttime < '" + WebUtility.InputText(this.tbEndTime.Text) + " 23:59:59'";
            CurrentMounthwhere += " and OrderDateTime < '" + WebUtility.InputText(this.tbEndTime.Text) + " 23:59:59'";
        }


        if (this.tbStartmounth.Text != "")
        {
            string Startmounth = this.tbStartmounth.Text + "-01";
            otherwhere += " and  [starttime] >= '" + Startmounth + "'";
            CurrentMounthwhere += " and  [OrderDateTime] >= '" + Startmounth + "' ";

        }
        if (this.tbEndmounht.Text != "")
        {
            string endmounth = Convert.ToDateTime(this.tbEndmounht.Text).AddMonths(1).AddSeconds(-1).ToString();
            otherwhere += " and starttime < '" + endmounth + "'";
            CurrentMounthwhere += " and OrderDateTime < '" + endmounth + "'";
        }

        //Response.Write(otherwhere+"      "+ CurrentMounthwhere);

        BindData();
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindData();
    }

    protected void rtpGifts_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //判断权限
        int _rs = WebUtility.checkOperator(4);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, "alert('无操作权限','success','true',5);init();");
            return;
        }
        if (e.CommandName == "Del")
        {
            if (dal.DelDeliver(Convert.ToInt32(e.CommandArgument)) > 0)
            {
                AlertScript.RegScript(this.Page, "showMessage('删除成功','success','true',5);init();");
                BindData();
            }
            else
            {
                AlertScript.RegScript(this.Page, "showMessage('删除失败','error','true',5);init();");
            }
        }
    }

    /// <summary>
    /// 导出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btExport_Click(object sender, EventArgs e)
    {
        org.in2bits.MyXls.XlsDocument doc = new XlsDocument();

        doc.FileName = "" + WebUtility.GetTime() + "配送员薪资结算.xls";
        doc.SummaryInformation.Author = "IHangjing"; //作者
        doc.SummaryInformation.Subject = "Order Record";
        doc.DocumentSummaryInformation.Company = "IHangjing.com";

        doc.Workbook.ProtectContents = true;
        string sheetName = "page";

        IList<DeliverInfo> alllist = dal.GetListWithOrderStatistics(1000, 1, SqlWhere, otherwhere, "ordercount");
        int allcount = 0;
        if (alllist.Count > 0)
        {
            allcount = alllist[0].recordtcount;
        }

        int pagegize = 30000;
        int pagecount = allcount / pagegize;
        if (allcount % pagegize != 0)
        {
            pagecount += 1;
        }


        for (int xx = 1; xx <= pagecount; xx++)
        {
            IList<DeliverInfo> list = new List<DeliverInfo>();
            for (int i = pagegize * (xx - 1); i < pagegize * xx && i < allcount; i++)
            {
                var item = alllist[i];
                list.Add(alllist[i]);
            }

            sheetName = "page" + xx;
            Worksheet sheet = doc.Workbook.Worksheets.Add(sheetName);
            Cells cells = sheet.Cells;

            int rowMin = 1;
            int colMin = 1;
            int colCount = 14;
            string cellName = "";  //列名
            object cellValue = ""; //列的值

            //设置列的格式
            ColumnInfo colInfo = new ColumnInfo(doc, sheet);//生成列格式对象
            colInfo.ColumnIndexStart = 0;
            colInfo.ColumnIndexEnd = 14;
            colInfo.Width = 5 * 1024;          //列的宽度计量单位为 1/256 字符宽
            sheet.AddColumnInfo(colInfo);

            for (int row = 0; row < list.Count + 1; row++)
            {
                if (row == 0)
                {
                    for (int col = 1; col <= colCount; col++)
                    {

                        switch (col)
                        {
                            case 1: cellName = "姓名"; break;
                            case 2: cellName = "城市"; break;
                            case 3: cellName = "群组"; break;
                            case 4: cellName = "岗位"; break;
                            case 5: cellName = "职位"; break;
                            case 6: cellName = "车辆所有人"; break;
                            case 7: cellName = "车辆"; break;
                            case 8: cellName = "级别"; break;
                            case 9: cellName = "配送费"; break;
                            case 10: cellName = "提成比例"; break;
                            case 11: cellName = "基本工资"; break;
                            case 12: cellName = "提成"; break;
                            case 13: cellName = "工资合计"; break;
                            case 14: cellName = "盈余"; break;
                           


                        }
                        org.in2bits.MyXls.Cell cell = cells.Add(rowMin + row, colMin + col - 1, cellName);//列名

                        cell.TopLineStyle = 2;
                        cell.TopLineColor = Colors.Black;
                        cell.BottomLineStyle = 2;
                        cell.BottomLineColor = Colors.Black;
                        if (col == 1)
                        {
                            cell.LeftLineStyle = 2;
                            cell.LeftLineColor = Colors.Black;
                        }
                        cell.RightLineStyle = 2;
                        cell.RightLineColor = Colors.Black;

                        cell.Font.Weight = FontWeight.Bold;
                        cell.Pattern = 1;
                        cell.PatternColor = Colors.Silver;

                    }
                }
                else
                {
                    for (int col = 1; col <= colCount; col++)
                    {

                        switch (col)
                        {
                            case 1: cellValue = list[row - 1].Name; break;
                            case 2: cellValue = list[row - 1].cityname; break;
                            case 3: cellValue = list[row - 1].Groupname.ToString(); break;
                            case 4: cellValue = WebHelper.Turntation(list[row - 1].reveint1); break;
                            case 5:
                                cellValue = WebHelper.TurnPost(list[row - 1].post);
                                break;
                            case 6: cellValue = WebHelper.TurnCarOwner(list[row - 1].carower);
                                break;
                            case 7: cellValue = list[row - 1].cartype; break;
                            case 8: cellValue = list[row - 1].grade.ToString()+"星"; break;
                            case 9: cellValue = list[row - 1].shopdiscountmoney; break;
                            case 10:
                                cellValue = list[row - 1].reveint3+"%";
                                break;
                            case 11: cellValue = list[row - 1].reveint2; break;
                            case 12: cellValue = list[row - 1].cut; break;
                            case 13: cellValue = list[row - 1].salary; break;
                            case 14: cellValue = list[row - 1].deliverprofit; break;
                           

                        }

                        org.in2bits.MyXls.Cell cell = cells.Add(rowMin + row, colMin + col - 1, cellValue);
                    }
                }

            }
        }

        doc.Send();     //将文档发送到浏览器
        Response.Flush();
        Response.End();

    }


}
